/*
 * @copyright 2011 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of GameTimer.
 *
 * GameTimer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GameTimer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GameTimer. If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiption.gametimer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.amphiption.gametimer.dao.PlayerDao;
import org.amphiption.gametimer.entity.Player;
import org.amphiption.gametimer.entity.TimerConfiguration;
import org.amphiption.gametimer.entity.TimerConfiguration.TimerType;
import org.amphiption.gametimer.view.PlayerView;
import org.amphiption.gametimer.view.PlayerView.OnPlayerClickedListener;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

/**
 * @author Amphiprion
 * 
 */
public class EditTimerConfiguration extends TabActivity implements OnPlayerClickedListener {
	private TimerConfiguration timer;
	private List<Player> players;
	private TextView lbDuration;
	private Spinner cbDuration;
	private EditText txtDuration;

	private Spinner cbReportLimit;
	private EditText txtReportLimit;
	private CheckBox chkReportLimit;
	private LinearLayout reportLimitLayout;
	private boolean reportLimit;

	private Spinner cbTimerType;
	private EditText txtName;
	private CheckBox chkHandicap;
	private boolean handicap;

	private CheckBox chkOwnTune;
	private boolean ownTune;
	private Button btOwnTune;
	private LinearLayout toneLayout;

	private CheckBox chkWarningTune;
	private boolean warningTune;
	private EditText txtBeforeWarning;
	private EditText txtEveryWarning;
	private Button btWarningTune;
	private LinearLayout warningLayout;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_timer_configuration);

		TabHost tabHost = getTabHost();
		tabHost.setup();

		TabSpec spec1 = tabHost.newTabSpec("Tab 1");
		spec1.setContent(R.id.tab1);
		spec1.setIndicator(getString(R.string.tab1Name));

		TabSpec spec2 = tabHost.newTabSpec("Tab 2");
		spec2.setIndicator(getString(R.string.tab2Name));
		spec2.setContent(R.id.tab2);

		TabSpec spec3 = tabHost.newTabSpec("Tab 3");
		spec3.setIndicator(getString(R.string.tab3Name));
		spec3.setContent(R.id.tab3);

		tabHost.addTab(spec1);
		tabHost.addTab(spec2);
		tabHost.addTab(spec3);

		Intent i = getIntent();
		String actionType = i.getStringExtra("TYPE");
		timer = (TimerConfiguration) i.getSerializableExtra("TIMER_CONFIGURATION");
		if (timer == null) {
			timer = new TimerConfiguration();
			timer.setTimerType(TimerType.TURN_TIMER);
			timer.setDuration(240);
			players = new ArrayList<Player>();
		} else {
			players = PlayerDao.getInstance(this).getPlayers(timer);
		}

		final LinearLayout lDuration = (LinearLayout) findViewById(R.id.duration_layout);
		chkReportLimit = (CheckBox) findViewById(R.id.chkReportLimit);
		txtReportLimit = (EditText) findViewById(R.id.txtReportLimit);
		cbReportLimit = (Spinner) findViewById(R.id.cbReportLimitType);
		reportLimitLayout = (LinearLayout) findViewById(R.id.reportLimitLayout);
		reportLimit = timer.getReportLimit() > 0 && timer.getTimerType() == TimerType.TURN_TIMER_SAVE;
		if (reportLimit) {
			chkReportLimit.setChecked(true);
			chkReportLimit.setVisibility(View.VISIBLE);
			reportLimitLayout.setVisibility(View.VISIBLE);

			if (timer.getReportLimit() / 60 * 60 == timer.getReportLimit()) {
				txtReportLimit.setText("" + timer.getReportLimit() / 60);
				cbReportLimit.setSelection(0);
			} else {
				txtReportLimit.setText("" + timer.getReportLimit());
				cbReportLimit.setSelection(1);
			}
		} else {
			chkReportLimit.setChecked(false);
			reportLimitLayout.setVisibility(View.GONE);
			if (timer.getTimerType() == TimerType.TURN_TIMER_SAVE) {
				chkReportLimit.setVisibility(View.VISIBLE);
			} else {
				chkReportLimit.setVisibility(View.GONE);
			}
		}
		chkReportLimit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				reportLimit = isChecked;
				if (!reportLimit) {
					reportLimitLayout.setVisibility(View.GONE);
				} else {
					reportLimitLayout.setVisibility(View.VISIBLE);
				}
			}
		});

		chkHandicap = (CheckBox) findViewById(R.id.chkHandicap);
		chkHandicap.setChecked(timer.isHandicap());
		handicap = timer.isHandicap();
		chkHandicap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				handicap = isChecked;
				LinearLayout ln = (LinearLayout) findViewById(R.id.player_list);
				for (int index = 0; index < ln.getChildCount(); index++) {
					((PlayerView) ln.getChildAt(index)).setHandicap(handicap);
				}

				if (!isChecked) {
					int duration = 0;
					if (txtDuration.getText().length() > 0) {
						duration = Integer.parseInt("" + txtDuration.getText());
						if (cbDuration.getSelectedItemPosition() == 0) {
							duration *= 60;
						}
					}
					for (Player p : players) {
						p.setDuration(duration);
					}
					lbDuration.setVisibility(View.VISIBLE);
					lDuration.setVisibility(View.VISIBLE);
				} else {
					lbDuration.setVisibility(View.GONE);
					lDuration.setVisibility(View.GONE);

				}

			}

		});

		chkOwnTune = (CheckBox) findViewById(R.id.chkOwnTune);
		btOwnTune = (Button) findViewById(R.id.btOwnTune);
		toneLayout = (LinearLayout) findViewById(R.id.toneLayout);
		ownTune = timer.getOwnTune() != null;
		if (!ownTune) {
			chkOwnTune.setChecked(false);
			toneLayout.setVisibility(View.GONE);
		} else {
			chkOwnTune.setChecked(true);
			toneLayout.setVisibility(View.VISIBLE);
			btOwnTune.setText(timer.getOwnTune());
		}
		chkOwnTune.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				ownTune = isChecked;
				if (!ownTune) {
					toneLayout.setVisibility(View.GONE);
				} else {
					toneLayout.setVisibility(View.VISIBLE);
				}
			}
		});
		btOwnTune.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				File file = Environment.getExternalStorageDirectory();
				intent.setDataAndType(Uri.parse(file.toString()), "text/*.mp3");

				try {
					startActivityForResult(intent, ApplicationConstants.ACTIVITY_RETURN_CHOOSE_FILE);
				} catch (ActivityNotFoundException e) {
					// No activity to handle this mime type.
					// Download for exemple ES File Manager
					askToDownloadFileManager();
				}
			}
		});

		chkWarningTune = (CheckBox) findViewById(R.id.chkAlert);
		txtBeforeWarning = (EditText) findViewById(R.id.txtStartWarning);
		txtEveryWarning = (EditText) findViewById(R.id.txtEveryWarning);
		btWarningTune = (Button) findViewById(R.id.btWarningTune);
		warningLayout = (LinearLayout) findViewById(R.id.warningLayout);
		warningTune = timer.getBeforeWarning() != 0;
		if (!warningTune) {
			chkWarningTune.setChecked(false);
			warningLayout.setVisibility(View.GONE);
			txtBeforeWarning.setText("0");
			txtEveryWarning.setText("1");
		} else {
			chkWarningTune.setChecked(true);
			warningLayout.setVisibility(View.VISIBLE);
			txtBeforeWarning.setText("" + timer.getBeforeWarning());
			txtEveryWarning.setText("" + timer.getEveryWarning());
			btWarningTune.setText(timer.getOwnTuneWarning());
		}
		chkWarningTune.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				warningTune = isChecked;
				if (!warningTune) {
					warningLayout.setVisibility(View.GONE);
				} else {
					warningLayout.setVisibility(View.VISIBLE);
				}
			}
		});
		btWarningTune.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				File file = Environment.getExternalStorageDirectory();
				intent.setDataAndType(Uri.parse(file.toString()), "text/*.mp3");

				try {
					startActivityForResult(intent, ApplicationConstants.ACTIVITY_RETURN_CHOOSE_FILE_WARNING);
				} catch (ActivityNotFoundException e) {
					// No activity to handle this mime type.
					// Download for exemple ES File Manager
					askToDownloadFileManager();
				}
			}
		});

		buildPlayerList();

		Button btStart = (Button) findViewById(R.id.btStart);
		Button btSave = (Button) findViewById(R.id.btSave);
		Button btCancel = (Button) findViewById(R.id.btCancel);
		TextView lbName = (TextView) findViewById(R.id.lbName);
		txtName = (EditText) findViewById(R.id.txtName);
		if ("LAUNCH".equals(actionType)) {
			btStart.setVisibility(View.VISIBLE);
			btSave.setVisibility(View.GONE);
			btCancel.setVisibility(View.GONE);
			txtName.setVisibility(View.GONE);
			lbName.setVisibility(View.GONE);
		} else {
			btStart.setVisibility(View.GONE);
			btSave.setVisibility(View.VISIBLE);
			btCancel.setVisibility(View.VISIBLE);
			txtName.setVisibility(View.VISIBLE);
			lbName.setVisibility(View.VISIBLE);
		}
		final Button btHelp = (Button) findViewById(R.id.btHelp);
		btHelp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showTimerHelp();
			}
		});

		cbTimerType = (Spinner) findViewById(R.id.cbTimerType);
		cbTimerType.requestFocus();
		cbDuration = (Spinner) findViewById(R.id.cbDurationType);
		txtDuration = (EditText) findViewById(R.id.txtDuration);
		txtName.setText(timer.getName());
		lbDuration = (TextView) findViewById(R.id.duration_label);

		if (timer.getDuration() / 60 * 60 == timer.getDuration()) {
			txtDuration.setText("" + timer.getDuration() / 60);
			cbDuration.setSelection(0);
		} else {
			txtDuration.setText("" + timer.getDuration());
			cbDuration.setSelection(1);
		}
		cbTimerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				TimerType tt = TimerType.values()[cbTimerType.getSelectedItemPosition()];
				if (tt == TimerType.UPCOUNT || tt == TimerType.TURN_COUNTER) {
					lbDuration.setVisibility(View.GONE);
					lDuration.setVisibility(View.GONE);
					chkHandicap.setVisibility(View.GONE);
					handicap = false;
					chkOwnTune.setVisibility(View.GONE);
					toneLayout.setVisibility(View.GONE);
					chkWarningTune.setVisibility(View.GONE);
					warningLayout.setVisibility(View.GONE);
					chkReportLimit.setVisibility(View.GONE);
				} else {
					handicap = chkHandicap.isChecked();
					if (tt == TimerType.SHARED_GAME_TIMER) {
						handicap = false;
						chkHandicap.setVisibility(View.GONE);
					} else {
						chkHandicap.setVisibility(View.VISIBLE);
					}
					if (handicap) {
						lbDuration.setVisibility(View.GONE);
						lDuration.setVisibility(View.GONE);
					} else {
						lbDuration.setVisibility(View.VISIBLE);
						lDuration.setVisibility(View.VISIBLE);
					}

					chkOwnTune.setVisibility(View.VISIBLE);
					ownTune = chkOwnTune.isChecked();
					if (ownTune) {
						toneLayout.setVisibility(View.VISIBLE);
					} else {
						toneLayout.setVisibility(View.GONE);
					}

					chkWarningTune.setVisibility(View.VISIBLE);
					warningTune = chkWarningTune.isChecked();
					if (warningTune) {
						warningLayout.setVisibility(View.VISIBLE);
					} else {
						warningLayout.setVisibility(View.GONE);
					}

					reportLimit = chkReportLimit.isChecked() && tt == TimerType.TURN_TIMER_SAVE;
					if (reportLimit) {
						chkReportLimit.setChecked(true);
						chkReportLimit.setVisibility(View.VISIBLE);
						reportLimitLayout.setVisibility(View.VISIBLE);
					} else {
						chkReportLimit.setChecked(false);
						reportLimitLayout.setVisibility(View.GONE);
						if (tt == TimerType.TURN_TIMER_SAVE) {
							chkReportLimit.setVisibility(View.VISIBLE);
						} else {
							chkReportLimit.setVisibility(View.GONE);
						}
					}

				}
				LinearLayout ln = (LinearLayout) findViewById(R.id.player_list);
				for (int index = 0; index < ln.getChildCount(); index++) {
					((PlayerView) ln.getChildAt(index)).setHandicap(handicap);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		cbTimerType.setSelection(timer.getTimerType().ordinal());

		btStart.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				boolean ok = updateTimer();
				if (ok) {
					// Intent i = new Intent(EditTimerConfiguration.this,
					// PlaySession.class);
					Intent i = new Intent(EditTimerConfiguration.this, PlaySessionNG.class);
					i.putExtra("TIMER_CONFIGURATION", timer);
					startActivity(i);
				}
			}
		});
		btSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				boolean ok = updateTimer();
				if (ok) {
					Intent i = new Intent();
					i.putExtra("TIMER_CONFIGURATION", timer);
					setResult(RESULT_OK, i);
					finish();
				}
			}
		});

		btCancel.setOnClickListener(new ViewGroup.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private boolean updateTimer() {
		boolean ok = false;
		int duration = 0;
		if (players.size() > 0) {
			TimerType tt = TimerType.values()[cbTimerType.getSelectedItemPosition()];
			if (tt == TimerType.UPCOUNT || tt == TimerType.TURN_COUNTER) {
				ok = true;
			} else if (txtDuration.getText().length() > 0) {
				duration = Integer.parseInt("" + txtDuration.getText());
				if (cbDuration.getSelectedItemPosition() == 0) {
					duration *= 60;
				}
				ok = true;
			}
		}

		if (ok) {
			// LinearLayout ln = (LinearLayout) findViewById(R.id.player_list);
			// for (int index = 0; index < ln.getChildCount() - 1; index++) {
			// ((PlayerView) ln.getChildAt(index)).updateData();
			// }
			timer.setTimerType(TimerType.values()[cbTimerType.getSelectedItemPosition()]);
			timer.setDuration(duration);
			timer.setName("" + txtName.getText());
			timer.setPlayers(players);
			timer.setHandicap(handicap);

			int reportLimitValue = 0;
			if (reportLimit && txtReportLimit.getText().length() > 0) {
				try {
					reportLimitValue = Integer.parseInt("" + txtReportLimit.getText());
					if (cbReportLimit.getSelectedItemPosition() == 0) {
						reportLimitValue *= 60;
					}
				} catch (Exception ee) {
				}
			}
			timer.setReportLimit(reportLimitValue);

			if (ownTune && btOwnTune.getText() != null && !"".equals("" + btOwnTune.getText())) {
				timer.setOwnTune("" + btOwnTune.getText());
			} else {
				timer.setOwnTune(null);
			}
			if (txtBeforeWarning.getText().length() > 0 && txtEveryWarning.getText().length() > 0) {
				timer.setBeforeWarning(Integer.parseInt("" + txtBeforeWarning.getText()));
				timer.setEveryWarning(Integer.parseInt("" + txtEveryWarning.getText()));
			} else {
				timer.setBeforeWarning(0);
			}
			if (warningTune && btWarningTune.getText() != null && !"".equals("" + btWarningTune.getText())) {
				timer.setOwnTuneWarning("" + btWarningTune.getText());
			} else {
				timer.setOwnTuneWarning(null);
			}

			if (!timer.isHandicap()) {
				for (Player p : players) {
					p.setDuration(duration);
				}
			}
		}
		return ok;
	}

	private void buildPlayerList() {
		LinearLayout ln = (LinearLayout) findViewById(R.id.player_list);
		ln.removeAllViews();
		for (Player player : players) {
			ln.addView(new PlayerView(this, player, this, handicap));
		}
		ln.addView(new PlayerView(this, null, this, handicap));
	}

	@Override
	public void playerClicked(PlayerView view) {
		LinearLayout ln = (LinearLayout) findViewById(R.id.player_list);
		if (view.getPlayer() == null) {
			ln.addView(new PlayerView(this, null, this, handicap));
			Player player = new Player();
			view.setPlayer(player);
			players.add(player);
		} else {
			players.remove(view.getPlayer());
			ln.removeView(view);
		}
	}

	private void showTimerHelp() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getResources().getString(R.string.timer_type_help));
		// .setCancelable(false).setPositiveButton("Yes", new
		// DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int id) {
		// MyActivity.this.finish();
		// }
		// }).setNegativeButton("No", new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int id) {
		// dialog.cancel();
		// }
		// });
		AlertDialog alert = builder.create();
		alert.show();
	}

	public void askToDownloadFileManager() {
		AlertDialog alertDialog = new AlertDialog.Builder(this).setMessage(R.string.install_file_chooser_message).create();
		alertDialog.setTitle(R.string.install_file_chooser_title);
		alertDialog.setIcon(android.R.drawable.ic_menu_info_details);
		alertDialog.setButton(getResources().getText(R.string.ok), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=lysesoft.andexplorer"));
				startActivity(marketIntent);
				return;
			}
		});
		alertDialog.setButton2(getResources().getText(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// do nothing
			}
		});
		alertDialog.show();
		return;

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == ApplicationConstants.ACTIVITY_RETURN_CHOOSE_FILE) {
				if (data.getDataString() != null && data.getDataString().toLowerCase().endsWith(".mp3")) {
					btOwnTune.setText(data.getDataString());
				} else {
					btOwnTune.setText("");
				}
			} else if (requestCode == ApplicationConstants.ACTIVITY_RETURN_CHOOSE_FILE_WARNING) {
				if (data.getDataString() != null && data.getDataString().toLowerCase().endsWith(".mp3")) {
					btWarningTune.setText(data.getDataString());
				} else {
					btWarningTune.setText("");
				}
			}
		}
	}

}